<template>
  <div class="condition-search-item">
    <div class="condition-search-item__field-select">
      <el-select
        v-model="conditionItem.fieldName"
        :placeholder="$t('common.placeholder.inputKeyWordToSearch')"
        filterable
        @change="() => selectFiled(true)"
      >
        <el-option
          v-for="field of fields"
          :key="field.fieldName"
          :label="field.displayName"
          :value="field.fieldName"
        ></el-option>
      </el-select>
    </div>
    <div class="condition-search-item__condition-select">
      <el-select
        v-model="conditionItem.operator"
        :disabled="!conditionItem.field"
        @change="() => changeCondition(true)"
      >
        <el-option
          v-for="field of conditionItem.operators"
          :key="field.value"
          :label="field.label"
          :value="field.value"
        ></el-option>
      </el-select>
    </div>
    <div class="condition-search-item__value">
      <component
        v-if="conditionItem.comp && conditionItem.operator"
        :is="conditionItem.comp"
        :label="conditionItem.field.displayName"
        :need-validate="false"
        :field="conditionItem.field"
        :value="conditionItem.value"
        :operator="conditionItem.operator"
        v-bind="conditionItem.bind"
        :no-default-country="noDefaultCountry"
        :picker-options="pickerOptions"
        :module="module"
        @update="changeValue"
      ></component>
      <el-input v-else disabled></el-input>
    </div>
  </div>
</template>
<script>
import { defineComponent, toRefs, unref, computed, nextTick } from 'vue';
// components
import FieldComponents from './FieldComponents';
// util
import { genComponent, initValue } from './advancedSearch';
import { getFieldOperator } from './operator';
import { getRootWindow } from '@src/util/dom';
import { t } from '@src/locales';
import { getTimestampAtStartOfDay, getTimestampAtEndOfDay } from '@src/util/lang/index';

export default defineComponent({
  name: 'ConditionSearchItem',
  components: {
    ...FieldComponents,
  },
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    conditionItem: {
      type: Object,
      default: () => ({
        field: {},
        fieldName: '',
      }),
    },
    // 远程搜索接口列表
    remoteMethod: {
      type: Object,
      default: () => ({}),
    },
    // 模块
    module: {
      type: String,
      default: '',
    },
    // 选择的单个条件所属模块
    conditionModule: {
      type: String,
      default: '',
    },
    ruleModule: {
      type: String,
      default: '',
    }
  },
  setup(props, { emit }) {
    const { conditionItem } = toRefs(props)

    /* 今天明天后天快捷选项  start */ 

    // 是否开启瑞尔特高级搜索灰度
    const isRuierteTaskSearchCondition = computed(() => {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.RUIERTE_TASK_SEARCH_CONDITION || false
    })
    // 是否显示今天明天后天快捷选项
    const showTaskSearchPickerOptions = computed(() => {
      const { fieldName, operator } = conditionItem.value || {};
      return isRuierteTaskSearchCondition.value && operator == 'between' && props.module == 'task' && ['planEndTime', 'createTime'].includes(fieldName);
    })
    // 时间快捷选项
    const pickerOptions = computed(() => {
      if (showTaskSearchPickerOptions.value) {
        return {
          shortcuts: [{
            text: t('common.base.aboutTime.today'),
            onClick(picker) {
              picker.$emit('pick', [getTimestampAtStartOfDay(0), getTimestampAtEndOfDay(0), 'today']);
            }
          }, {
            text: t('common.base.aboutTime.tomorrow'),
            onClick(picker) {
              picker.$emit('pick', [getTimestampAtStartOfDay(1), getTimestampAtEndOfDay(1), 'tomorrow']);
            }
          }, {
            text: t('common.base.aboutTime.dayAfterTomorrow'),
            onClick(picker) {
              picker.$emit('pick', [getTimestampAtStartOfDay(2), getTimestampAtEndOfDay(2), 'dayAfterTomorrow']);
            }
          }]
        }
      }
      return {};
    })

    /* 今天明天后天快捷选项  end */ 

    // 字段map
    let fieldMap = computed(() => {
      const map = {};
      props.fields.forEach(item => {
        if (item.fieldName === 'area' && item.formType === 'select') {
          // 客户表单服务器生成的区域字段
          // 原先叫area会去重导致没有添加进去，这里改个名字，在搜索的时候进行转换回area处理
          item.fieldName = 'customerAreaSelect';
        }
        if (!map[item.fieldName]) {
          map[item.fieldName] = item;
        }
      });
      return map;
    });

    /**
     * 选中field
     * @param {Boolean} needDefaultCondition 是否继续操作默认条件
     */
    async function selectFiled(needDefaultCondition = true) {
      const { fieldName } = unref(conditionItem);
      const field = fieldMap.value[fieldName];
      conditionItem.value.field = field;
      conditionItem.value.operators = getFieldOperator(field, props.module, props.conditionModule);
      // 特殊处理回执金额的operators，移除包含
      if(props.ruleModule === 'task_receipt_amount' && field?.formType === 'number') {
        conditionItem.value.operators = conditionItem.value.operators?.filter(item => item.value !== 'like')
      }
      if(!needDefaultCondition) return
      conditionItem.value.operator = unref(conditionItem).operators?.[0].value;
      conditionItem.value.comp = null;
      emit('selectFiled', fieldName);
      emit('selectFiledChange', field);
      await nextTick();
      changeCondition();
    }

    /**
     * 切换条件（等于……）
     * 生成对应组件、props、初始值
     * @param {Boolean} needInitValue 是否初始化value
     */
    function changeCondition(needInitValue = true) {
      const { field, operator } = unref(conditionItem);
      const { component, bind } = genComponent({
        remoteMethod: props.remoteMethod,
        field,
        operator,
      });
      conditionItem.value.bind = bind;
      conditionItem.value.comp = component;
      if(!needInitValue) return
      conditionItem.value.value = initValue(unref(conditionItem))
      emit('changeCondition', unref(conditionItem).value);
    }

    /**
     * 修改value
     * @param {*} value 组件回传值
     */
    function changeValue(value) {
      if (showTaskSearchPickerOptions.value) {
        if (value && value.length) {
          conditionItem.value.timeType = value[2];
          value = [value[0], value[1]];
        } else {
          conditionItem.value.timeType = '';
        }
      } else {
        conditionItem.value.timeType = '';
      }
      conditionItem.value.value = value;
      emit('changeValue', value);
    }

    /**
     * 初始化条件
     */
    function initConditionField() {
      const { fieldName, operator, value } = conditionItem.value || {};
      if (fieldName) {
        // 有条件不用走默认流程
        selectFiled(!operator)
        // 有条件和值不需要初始化值
        changeCondition(!operator && value !== null)
      }
    }

    {
      initConditionField(); // 初始化条件
    }

    const noDefaultCountry = computed(() => {
      return conditionItem.value.field?.fieldName === 'productCompleteAddress' ? true : undefined
    })

    return {
      selectFiled,
      pickerOptions,
      changeCondition,
      changeValue,
      noDefaultCountry
    };
  },
});
</script>
<style lang="scss">
.condition-search-item {
  flex: 1;
  display: flex;
  align-items: center;

  &__field-select {
    .el-select {
      width: 150px;
    }
  }

  &__condition-select {
    margin: 0 12px;

    .el-select {
      width: 100px;
    }
  }

  &__value {
    flex: 1;

    .el-input,
    .el-select,
    .el-date-picker,
    .el-date-editor,
    .el-cascader {
      width: 100% !important;
    }
  }
  .condition-search-item__value{
    .international-pick{
      display: flex;
      .country-cls{
        margin:0 12px 0 0 !important;
      }
    }
  }
}
</style>
